#include "thread_pool.hpp"
#include <iostream>
#include <chrono>
#include <thread>
#include <cassert>

using namespace timeout_manager;

// g++ -std=c++17 -pthread -o test_thread_pool test_thread_pool.cpp thread_pool.cpp

// 测试函数：简单的计算任务
int calculate(int a, int b) {
    std::cout << "计算 " << a << " + " << b << std::endl;
    // 模拟一些计算时间
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return a + b;
}

// 测试函数：无返回值任务
void printMessage(const std::string& message) {
    std::cout << "消息: " << message << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
}

void testBasicSubmit() {
    std::cout << "\n=== 测试基本任务提交 ===" << std::endl;
    
    // 创建小线程池（2个线程）便于观察
    ThreadPool pool(2);
    
    // 提交几个简单任务
    for (int i = 0; i < 5; ++i) {
        pool.submit([i]() {
            std::cout << "执行任务 " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            std::cout << "任务 " << i << " 完成" << std::endl;
        });
    }
    
    // 检查队列大小
    std::cout << "当前队列大小: " << pool.getQueueSize() << std::endl;
    
    // 等待任务完成
    std::this_thread::sleep_for(std::chrono::milliseconds(600));
    std::cout << "基本任务测试完成" << std::endl;
}

void testSubmitWithResult() {
    std::cout << "\n=== 测试带返回值的任务 ===" << std::endl;
    
    ThreadPool pool(2);
    
    // 提交带返回值的任务
    auto future1 = pool.submitWithResult(calculate, 10, 20);
    auto future2 = pool.submitWithResult(calculate, 5, 15);
    
    // 提交无返回值的任务
    pool.submit([](){ printMessage("Hello from thread pool!"); });
    
    // 获取结果
    try {
        int result1 = future1.get();  // 阻塞等待结果
        int result2 = future2.get();
        
        std::cout << "结果1: " << result1 << std::endl;
        std::cout << "结果2: " << result2 << std::endl;
        
        // 验证结果
        assert(result1 == 30);
        assert(result2 == 20);
        std::cout << "✓ 计算结果正确" << std::endl;
        
    } catch (const std::exception& e) {
        std::cout << "获取结果时发生异常: " << e.what() << std::endl;
    }
}

void testExceptionHandling() {
    std::cout << "\n=== 测试异常处理 ===" << std::endl;
    
    ThreadPool pool(1);
    
    // 提交一个会抛出异常的任务
    auto future = pool.submitWithResult([]() -> int {
        std::cout << "即将抛出异常..." << std::endl;
        throw std::runtime_error("测试异常");
        return 42;  // 不会执行到这里
    });
    
    try {
        int result = future.get();
        std::cout << "意外得到结果: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cout << "✓ 成功捕获异常: " << e.what() << std::endl;
    }
    
    // 提交一个普通任务，确保线程池仍然工作
    auto future2 = pool.submitWithResult([]() { return 100; });
    int result = future2.get();
    assert(result == 100);
    std::cout << "✓ 异常后线程池仍正常工作" << std::endl;
}

int main() {
    std::cout << "开始测试线程池..." << std::endl;
    
    testBasicSubmit();
    testSubmitWithResult();
    testExceptionHandling();
    
    std::cout << "\n所有线程池测试通过！" << std::endl;
    return 0;
}